﻿using BingSpatialDataServiceExcelAddin.BSDSTools.Models;
using System;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace BingSpatialDataServiceExcelAddin.Views
{
    /// <summary>
    /// Interaction logic for DataSourceJobListBox.xaml
    /// </summary>
    public partial class DataSourceJobListBox : UserControl
    {
        public DataSourceJobListBox()
        {
            InitializeComponent();
        }

        private void DetailsBtn_Click(object sender, RoutedEventArgs e)
        {
            Button b = sender as Button;
            DataflowJob job = b.Tag as DataflowJob;

            StringBuilder sb = new StringBuilder();

            WriteLine("ID", job.Id, sb);
            WriteLine("Name", job.Name, sb);
            WriteLine("Job Description", job.Description, sb);
            WriteLine("Status", job.Status, sb);
            WriteLine("Created Date", job.CreatedDate, sb);
            WriteLine("Completed Date", job.CompletedDate, sb);

            if (job.TotalEntityCount > 0)
            {
                sb.AppendFormat("Total Entity Count: {0}\r\n", job.TotalEntityCount);
                sb.AppendFormat("Processed Entity Count: {0}\r\n", job.ProcessedEntityCount);
                sb.AppendFormat("Failed Entity Count: {0}\r\n", job.FailedEntityCount);                
            }

            if (job.Links != null &&
                job.Links.Length > 0)
            {
                foreach (var l in job.Links)
                {
                    WriteLink(l, sb);
                }
            }

            OutputModal form = new OutputModal("Job Details", sb.ToString());
            System.Windows.Forms.NativeWindow xlMain = new System.Windows.Forms.NativeWindow();
            xlMain.AssignHandle(new IntPtr(Globals.ThisAddIn.Application.Hwnd));

            form.ShowDialog(xlMain);
            form.Dispose();
            xlMain.ReleaseHandle();
        }

        private void WriteLine(string name, string value, StringBuilder sb)
        {
            if(!string.IsNullOrWhiteSpace(value)){
                sb.AppendFormat("{0}: {1}\r\n", name, value);
            }
        }

        private void WriteLink(Link link, StringBuilder sb)
        {
            sb.AppendFormat("Link:\r\n\tName: {0}\r\n\tRole: {1}\r\n\tURL: {2}\r\n", link.Name, link.Role, link.URL);
        }
    }
}
